package com.h5lib.nchuoffice;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import com.h5lib.jdbc.ormlite.SqliteJdbcConnectionSource;
import com.h5lib.nchuoffice.app.action.CourseAction;
import com.h5lib.nchuoffice.app.action.GradeAction;
import com.h5lib.nchuoffice.app.action.HomeAction;
import com.h5lib.nchuoffice.app.action.LoginAction;
import com.h5lib.nchuoffice.app.dao.CacheDao;
import com.h5lib.nchuoffice.app.interceptor.AuthInterceptor;
import com.h5lib.server.CoreWebServer;
import com.h5lib.server.Di.CoreConfig;
import com.h5lib.server.DiApp;
import com.h5lib.server.DiException;

/**
 * 
 * @author framer
 *
 */
public class App extends DiApp
{	
	
	public App(String[] args) throws DiException {
		super(args);
	}

	@Override
	public void startApp(){
		if(NetUtil.internalIp()){	//判断是否为内网
			NetUtil.setProxy("10.50.152.250", "8080");
		}
		int port = 8082;
		if(args != null && args.length > 0 && args[0] != null){
			port = Integer.valueOf(args[0]);
		}
		CoreWebServer server = new CoreWebServer(port);
		server.addInterceptor(new AuthInterceptor());
	    try {
	        server.start();
	    } catch (IOException ioe) {
	        System.err.println("Couldn't start server:\n" + ioe);
	        System.exit(-1);
	    }
	    try {
			Class.forName("android.os.Build");
			 System.out.println("Android Os Server started.\n");
		} catch (ClassNotFoundException e) {
	        System.out.println("desktop Os Server started, Hit Enter to stop.\n");
	        try {
	            System.in.read();
	        } catch (Throwable ignored) {
	        }
	        server.stop();
	        System.out.println("Server stopped.\n");
		}
	}
	
	@Override
	public void initDi() throws  DiException {
    	String db = args.length>1 ? args[1]: System.getProperty("user.home")+"/nchu_cache.db";
		if(!new File(db).getParentFile().exists()){
			new File(db).getParentFile().mkdirs();
		}
    	String jdbc = "jdbc:sqlite:"+db;
    	try {
			CoreConfig.IOC.put(SqliteJdbcConnectionSource.class, new SqliteJdbcConnectionSource(jdbc));
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DiException();
		}
    	CoreConfig.iocClasses.add(LoginAction.class);
    	CoreConfig.iocClasses.add(HomeAction.class);
    	CoreConfig.iocClasses.add(GradeAction.class);
    	CoreConfig.iocClasses.add(CourseAction.class);
    	CoreConfig.iocClasses.add(CacheDao.class);
	}
	
	/**
	 * 入口
	 * @param args
	 * @throws DiException
	 * @throws SQLException
	 */
    public static void main(String[] args) throws DiException, SQLException {
    	new App(args);
	}
}
